/**
 * 音频频率可视化
 */
import * as THREE from '../../build/three.module.js';
import { OrbitControls } from '../../jsm/controls/OrbitControls.js';

const fftSize = 128;

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xefefff);

/**
 * 构建可视化图形
 */
const group = new THREE.Group();
for(let i = 0; i < fftSize / 2; i += 1) {
  const box = new THREE.BoxGeometry(10, 100, 10);
  const mat = new THREE.MeshPhongMaterial({
    color: 0x0000ff,
    side: THREE.DoubleSide
  })
  const mesh = new THREE.Mesh(box, mat);
  mesh.position.set(i * 20 - fftSize / 2 * 10, 0, 0);
  group.add(mesh);
}
scene.add(group);

const ab = new THREE.AmbientLight(0xffffff);
scene.add(ab);

const axesH = new THREE.AxesHelper(200);
scene.add(axesH);

const k = innerWidth / innerHeight,
      s = 75,
      camera = new THREE.PerspectiveCamera(s, k, 1, 10000);
camera.position.set(0, 0, 400);
camera.lookAt(scene.position);

/**
 * 构建音频
 */
let analyser = null;
const linstener = new THREE.AudioListener();
const audio = new THREE.Audio(linstener);
const audioLoader = new THREE.AudioLoader();
audioLoader.load('../../sounds/358232_j_s_song.mp3', ab => {
  audio.setBuffer(ab);
  audio.setLoop(true);
  audio.setVolume(.5);
  audio.play();
  // 创建音频分析器
  analyser = new THREE.AudioAnalyser(audio, fftSize * 2);
});

const renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

new OrbitControls(camera, renderer.domElement);

let arr;
const renderAnalyser = () => {
  // 获取频率数据
  arr = analyser.getFrequencyData();
  // getAverageFrequency()返回平均音频
  // var frequency = analyser.getAverageFrequency();
  // 遍历网格子对象，设置频率数据
  group.children.forEach((el, i) => {
    el.scale.y = arr[i] === 0 ? .001 : arr[i] / 80; // 为什么是80
    el.material.color.r = arr[i] / 200;
  });
}

(function render(){
  requestAnimationFrame(render);
  renderer.render(scene, camera);
  if (analyser) {
    renderAnalyser();
  }
})();